-- UIStoneSelectTarget
-- Created by chengb May/22/2015
-- 石柱选择目标界面

UIStoneSelectTarget = class("UIStoneSelectTarget", function()
    return cc.Layer:create();
end);

function UIStoneSelectTarget.create(skillId)
    return UIStoneSelectTarget.new(skillId);
end

function UIStoneSelectTarget:ctor(skillId)
    -- 初始化
    self:setName("UIStoneSelectTarget");

    local node = cc.CSLoader:createNode("layout/common/CommSelectTarget.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.skillId = skillId;
    self.bine    = ME.user.bine;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIStoneSelectTarget:resize()
    local node = self.node;
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local scaleX = w / DESIGN_WIDTH;

    -- CT底部居中并缩放至合适大小
    AlignM.alignToBottomCenter(node, "CT");

    -- CT2顶部居中并缩放至合适大小
    AlignM.alignToTopCenter(node, "CT2");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIStoneSelectTarget:redraw()
    -- 技能效果
    local skillId = self.skillId;
    local effect = findChildByName(self.node, "CT2/desc");
    local effectText = SkillM.getSkillDesc(skillId);
    effectText = string.gsub(effectText, "%[blue]", "[light_green]");
    TextStyleM.setTextStyle(effect, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW);
    applyString(effect, effectText);

    -- 提示信息
    local tipLabel = findChildByName(self.node, "CT/tip");
    TextStyleM.setTextStyle(tipLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW);
    tipLabel:setString(getLocStr("select_target_tip"));

    local costImg = findChildByName(self.node, "CT/lanping");
    local costLabel  = findChildByName(self.node, "CT/lanping/cost");
    local curMpLabel = findChildByName(self.node, "CT/lanping/max")
    local requireMp = 0;
    local curMp = 0;

    if MagicStoneM.isStoneSkill(skillId) then
        -- 石柱技能

        -- 计算施法消耗
        requireMp = MagicStoneM.calcSkillCost(self.skillId);

        -- 获取当前魔法值
        curMp = ME.user:getMp();
        costImg:loadTexture(getLargeAttribIconPath("mp"));

    elseif SlimeSkillM.isSlimeSkill(skillId) then
        -- 冈布奥专属技能

        local slimeSkillId = SlimeSkillM.getSlimeActiveSkillId(skillId);

        -- 获取当前能量
        local energy = SlimeSkillM.calcUserEnergyCost(slimeSkillId);

        local key = table.keys(energy)[1];
        requireMp = table.values(energy)[1];
        if type(key) == 'number' then
            curMp = ItemM.getAmount(ME.user, key);
            local iconPath = getItemIconPath(ItemM.query(key, "icon"));
            costImg:loadTexture(iconPath);
        else
            curMp = DungeonServiceM.queryDungeonAttrib(key);
            costImg:loadTexture(getLargeAttribIconPath("energe"));
        end

        local dbase = SlimeSkillM.query(slimeSkillId, "dbase") or {};
        if dbase["cost_all"] then
            -- 如果是消耗全部属性的，至少为1
            requireMp = curMp;
            requireMp = math.max(requireMp, 1);
        end

    elseif SlimeSkillM.isDragonMagic(skillId) then
        -- 龙语魔法
        local dragonMagicId = SlimeSkillM.getDragonMagicSkillId(skillId);

        -- 获取当前能量
        local energy = SlimeSkillM.calcUserEnergyCost(dragonMagicId);

        local key = table.keys(energy)[1];
        requireMp = table.values(energy)[1];
    else
        -- 暂时只有元素球
        local spellId = SpellM.getSpellId(skillId);
        if spellId then
            requireMp = SpellM.calcSpellCost(spellId) or 0;
            -- 获取当前魔法值
            curMp = ME.user:getMp();
        end
        costImg:loadTexture(getLargeAttribIconPath("mp"));
    end

    -- 显示为正数
    requireMp = math.abs(requireMp);

    TextStyleM.setTextStyle(costLabel, TextStyleM.TEXT_SIZE_MIDDLE2, TextStyleM.TEXT_COLOR_WHITE, true, -4);
    TextStyleM.setTextStyle(curMpLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true, -4);
    costLabel:setString(tostring(requireMp));
    curMpLabel:setString("/" .. curMp);

    -- 获取作用目标类型
    local targetType = SkillM.query(self.skillId, "target");
    self.targetType = targetType;

    -- 设置技能名字及施放目标
    local nameLabel = findChildByName(self.node, "CT/tip");
    local skillName = SkillM.query(self.skillId, "name");

    if targetType == ATTACKER then
        -- 对自身施放
        skillName = skillName .. getLocStr("no_select_target");
    elseif targetType == DEFENSER then
        -- 对敌方施放
        -- 主动技能，选择目标
        skillName = skillName .. getLocStr("select_target");
    else
        trace("UIStoneSelectTarget", "技能target类型不支持，请检查配置")
    end
    nameLabel:setString(skillName);

    -- 显示遮罩
    self:showMask();

    -- 处于变身状态，创建变身状态的模型，否则创建普通模型
    local shapeId = ShapeChangeM.getShapeChangeId();
    if type(shapeId) == "number" and shapeId ~= -1 then
        -- 获取当前的出战宠物
        local pet = ME.user:getActivePet();
        local userPetId = pet.classId;

        self:createShapeChangeModel(shapeId);
    else
        -- 创建英雄模型
        self:createHeroModel();
    end
end

-- 创建英雄模型
function UIStoneSelectTarget:createHeroModel()
    local headImg   = findChildByName(self.node, "CT/head_icon");
    local modelNode = findChildByName(self.node, "CT/model_node");

    -- 获取当前出战英雄
    local pet = ME.user:getActivePet();
    local classId = pet.classId;
    local petInfo = PetM.queryModel(pet:getModelId());

    local iconPath = getHeroIconPath(pet:getIcon());
    modelNode:removeAllChildren();
    createHeroModel(pet:getModelId(), headImg, modelNode, petInfo["model_scale"], iconPath);
end

-- 创建变身后的英雄模型
function UIStoneSelectTarget:createShapeChangeModel(shapeId)
    local headImg   = findChildByName(self.node, "CT/head_icon");
    local modelNode = findChildByName(self.node, "CT/model_node");

    -- 查询变身信息
    local shapeInfo = ShapeChangeM.query(shapeId);

    -- 获取当前出战英雄
    local iconPath = getHeroLargeIconPath(shapeInfo["icon"]);
    local animation = shapeInfo["animation"];
    modelNode:removeAllChildren();
    createShapeChangeMode(shapeId, headImg, animation, modelNode, shapeInfo["model_scale"], iconPath);
end

-- 显示蒙版
function UIStoneSelectTarget:showMask()
    showTargetSelectMask(self.targetType);
end

-- 隐藏蒙版
function UIStoneSelectTarget:hideMask()
    hideTargetSelectMask();
end

-- 施放
function UIStoneSelectTarget:applySkill(skillId, pos)
    if MagicStoneM.isStoneSkill(skillId) then
        -- 石柱技能
        local ret = MagicStoneM.checkApply(skillId);
        if ret == "full_attrib" then
            -- 提示属性达到上限，无法使用
            alert(getLocStr("full_attrib"));
            return
        elseif ret ~= true then
            -- 提示无法使用
            -- 其他情况暂时仅提示魔法不足
            alert(getLocStr("no_enough_mp"));
            return;
        end

        -- 使用技能
        DungeonActionM.go("stone_skill", pos, nil, skillId);
        EventMgr.fire(event.PLAYER_MOVE, pos);

    elseif SlimeSkillM.isSlimeSkill(skillId) then
        -- TODO: 冈布奥主动技能
        local result = SlimeSkillM.canApply(pos, SlimeSkillM.getSlimeActiveSkillId(skillId));

        if true == result then
            local function useSkill()
                DungeonActionM.go("use_slime_skill", pos, skillId);
                if not SlimeSkillM.isNeedDelay(skillId) then
                    EventMgr.fire(event.PLAYER_MOVE, pos);
                end
            end

            local dbase = SlimeSkillM.query(SlimeSkillM.getIdBySkill(skillId), "dbase") or {};
            if 1 == dbase["call_airship"] then
                -- 弹出对话
                local data = ME.user.dbase:query("dungeon_sc_data") or {};
                local shipId = data["ship_id"] or ME.user.dbase:query("active_airship");
                local shipName = NewAirShipM.query(shipId, "name") or "";
                startDialogueTemplate("airship_console", useSkill,
                    {["ship_name"] = shipName, ["area_name"] = DungeonAreaM.query(1003,"name")});
            else
                useSkill();
            end
        elseif type(result) == "string" then
            alert(result);
        end

    elseif SlimeSkillM.isDragonMagic(skillId) then
        local result = SlimeSkillM.canApply(pos, SlimeSkillM.getDragonMagicSkillId(skillId));
        if true == result then
            DungeonActionM.go("use_slime_skill", pos, skillId);
            EventMgr.fire(event.PLAYER_MOVE, pos);
        elseif type(result) == "string" then
            alert(result);
        end
    else
        -- 暂时只有元素球
        local spellId = SpellM.getSpellId(skillId);
        if spellId then
            DungeonActionM.go("use_spell", pos, spellId);
            EventMgr.fire(event.PLAYER_MOVE, pos);
        end
    end
end

-- 无目标施法
function UIStoneSelectTarget:useSkillWithoutTarget()
    if self.targetType == ATTACKER then
        -- 被动技能，不需要选择目标
        self:applySkill(self.skillId, -1);
    end
end

-- 注册点击事件
function UIStoneSelectTarget:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIStoneSelectTarget");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 注册事件处理回调函数
function UIStoneSelectTarget:registerEventCallback()
    EventMgr.register("UIStoneSelectTarget", event.TARGET_SELECTED, function(pos)
        -- 获取所有已开启的怪物格子
        local openMonsterGrids = UIDungeonMgr:getCurLevel():getOpenMonsterGrids();
        local castFlag = false;

        for i = 1, #openMonsterGrids do
            if openMonsterGrids[i].index == pos then
                if self.targetType ~= ATTACKER then
                    -- 判断能否使用技能
                    local grid = DungeonM.getGridByPos(pos);
                    if not grid then
                        cclog("格子(%d)不存在", pos);
                        return;
                    end

                    -- 施放
                    self:applySkill(self.skillId, pos);

                    castFlag = true;
                end

                break;
            end
        end

        -- 尝试无目标施法
        if not castFlag then
            self:useSkillWithoutTarget();
        end

        self:hideMask();

        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIStoneSelectTarget");
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIStoneSelectTarget 界面析构清理");
            self:hideMask();

            EventMgr.removeAll("UIStoneSelectTarget");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

        elseif ev == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end




